<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/6/14
 * Time: 17:51
 */

namespace Weixin\Service;


use Common\Common\Service;
use Weixin\Component\Weixin\WeixinComponent;
use Weixin\Exception\WeixinException;
use Weixin\Request\Weixin\UpdateWeixinRequest;
use Weixin\Response\UpdateWeixinResponse;

class UpdateWeixinService implements Service
{
    public function run(UpdateWeixinRequest $request = null)
    {
        if ($request->issetOpenId() == false) {
            throw new WeixinException(10001);
        }
        if ($request->issetSubscribe() == false) {
            throw new WeixinException(10001);
        }
        if ($request->issetUpdateTime() == false) {
            throw new WeixinException(10001);
        }
        if ($request->verifySubscribe() == false) {
            throw new WeixinException(10002);
        }
        if ($request->verifyUpdateTime() == false) {
            throw new WeixinException(10002);
        }

        $openid = $request->getOpenId();
        $nickname = $request->getNickName();
        $update_time = $request->getUpdateTime();
        $headimgurl = $request->getHeadImgUrl();
        $subscribe = $request->getSubscribe();

        $response = new UpdateWeixinResponse();
        $component = new WeixinComponent();
        try {
            $result = $component->updateWeixin($openid, $nickname, $update_time, $headimgurl, $subscribe);
            if (!$result) {
                $response->setItIsNull();
            }
        } catch (WeixinException $e) {
            throw new WeixinException($e->getMessage(), $e->getCode());
        }
        return $response;
    }
}